<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETF行业配置详情</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1200px;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #409eff;
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 20px;
            font-size: 16px;
            font-weight: 500;
        }
        .card-body {
            padding: 20px;
        }
        .chart-container {
            height: 400px;
            margin-bottom: 20px;
        }
        .btn-primary {
            background-color: #409eff;
            border-color: #409eff;
        }
        .btn-primary:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #ebeef5;
        }
        .info-item:last-child {
            border-bottom: none;
        }
        .info-label {
            color: #606266;
            font-weight: 500;
        }
        .info-value {
            color: #303133;
            font-weight: 600;
        }
        .back-btn {
            margin-bottom: 20px;
        }
        .loading {
            text-align: center;
            padding: 60px;
            color: #909399;
        }
        .form-control {
            border-radius: 4px;
            border: 1px solid #dcdfe6;
        }
        .form-control:focus {
            border-color: #409eff;
            outline: none;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
        .date-range-picker {
            margin-bottom: 20px;
        }
        .highlight-box {
            background-color: #f0f9ff;
            border: 1px solid #d9ecff;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .highlight-box h4 {
            color: #409eff;
            margin-bottom: 15px;
        }
        .trend-indicator {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }
        .trend-up {
            background-color: #f0f9ff;
            color: #409eff;
        }
        .trend-down {
            background-color: #fef0f0;
            color: #f56c6c;
        }
        .trend-flat {
            background-color: #f4f4f5;
            color: #909399;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <button class="btn btn-primary back-btn" onclick="window.history.back();">
            <i class="fa fa-arrow-left mr-2"></i>返回列表
        </button>
        
        <h2 class="text-center mb-5">ETF行业配置详情分析</h2>
        
        <!-- 查询条件 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-search mr-2"></i>查询条件
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="blockCode">板块代码：</label>
                            <input type="text" id="blockCode" class="form-control" placeholder="请输入板块代码">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="startDate">开始日期：</label>
                            <input type="date" id="startDate" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="endDate">结束日期：</label>
                            <input type="date" id="endDate" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12 text-center">
                        <button id="queryBtn" class="btn btn-primary">
                            <i class="fa fa-search mr-2"></i>查询
                        </button>
                        <button id="resetBtn" class="btn btn-default ml-2">
                            <i class="fa fa-refresh mr-2"></i>重置
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 基础信息 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-info-circle mr-2"></i>行业配置基本信息
            </div>
            <div class="card-body">
                <div id="basicInfo" class="loading">
                    <i class="fa fa-spinner fa-spin fa-2x mr-2"></i>
                    <span>加载中...</span>
                </div>
            </div>
        </div>
        
        <!-- 趋势图表 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-line-chart mr-2"></i>配置比例趋势
            </div>
            <div class="card-body">
                <div id="trendChart" class="chart-container"></div>
            </div>
        </div>
        
        <!-- 对比图表 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-bar-chart mr-2"></i>环比分析
            </div>
            <div class="card-body">
                <div id="compareChart" class="chart-container"></div>
            </div>
        </div>
        
        <!-- 历史数据表格 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-table mr-2"></i>历史配置数据
            </div>
            <div class="card-body">
                <div id="historyTableContainer">
                    <div class="loading">
                        <i class="fa fa-spinner fa-spin fa-2x mr-2"></i>
                        <span>加载中...</span>
                    </div>
                    <table class="table table-striped table-hover" id="historyTable" style="display: none;">
                        <thead>
                            <tr>
                                <th>报告日期</th>
                                <th>板块占比(%)</th>
                                <th>环比变化(%)</th>
                                <th>变化趋势</th>
                                <th>更新时间</th>
                            </tr>
                        </thead>
                        <tbody id="historyTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 设置默认日期范围（最近3个月）
            const today = new Date();
            const threeMonthsAgo = new Date();
            threeMonthsAgo.setMonth(today.getMonth() - 3);
            
            $('#startDate').val(threeMonthsAgo.toISOString().split('T')[0]);
            $('#endDate').val(today.toISOString().split('T')[0]);
            
            // 初始化图表
            const trendChart = echarts.init(document.getElementById('trendChart'));
            const compareChart = echarts.init(document.getElementById('compareChart'));
            
            // 绑定查询按钮事件
            $('#queryBtn').click(queryData);
            
            // 绑定重置按钮事件
            $('#resetBtn').click(function() {
                $('#blockCode').val('');
                $('#startDate').val(threeMonthsAgo.toISOString().split('T')[0]);
                $('#endDate').val(today.toISOString().split('T')[0]);
            });
            
            // 初始查询
            queryData();
            
            // 查询数据
            function queryData() {
                const blockCode = $('#blockCode').val();
                const startDate = $('#startDate').val();
                const endDate = $('#endDate').val();
                
                if (!startDate || !endDate) {
                    alert('请选择日期范围');
                    return;
                }
                
                $.ajax({
                    url: '/etfblock/listByDateRange?startDate=' + startDate + '&endDate=' + endDate,
                    type: 'GET',
                    success: function(data) {
                        // 如果指定了板块代码，则过滤数据
                        let filteredData = data;
                        if (blockCode) {
                            filteredData = data.filter(item => item.blockCode === blockCode);
                        }
                        
                        // 更新基本信息
                        updateBasicInfo(filteredData);
                        
                        // 更新趋势图
                        updateTrendChart(filteredData);
                        
                        // 更新对比图
                        updateCompareChart(filteredData);
                        
                        // 更新历史数据表
                        updateHistoryTable(filteredData);
                    },
                    error: function() {
                        alert('查询失败，请稍后重试');
                    }
                });
            }
            
            // 更新基本信息
            function updateBasicInfo(data) {
                if (!data || data.length === 0) {
                    $('#basicInfo').html('<div class="text-center text-danger">暂无数据</div>');
                    return;
                }
                
                // 按日期排序，取最新的数据
                data.sort((a, b) => new Date(b.reportDate) - new Date(a.reportDate));
                const latestData = data[0];
                
                // 计算统计数据
                const blockCode = latestData.blockCode;
                const totalRecords = data.length;
                const avgRatio = data.reduce((sum, item) => sum + (item.blockRatio || 0), 0) / totalRecords;
                const maxRatio = Math.max(...data.map(item => item.blockRatio || 0));
                const minRatio = Math.min(...data.map(item => item.blockRatio || 0));
                
                // 计算趋势
                let trend = 'flat';
                let trendChange = 0;
                if (data.length >= 2) {
                    const currentRatio = latestData.blockRatio || 0;
                    const previousRatio = data[1].blockRatio || 0;
                    trendChange = currentRatio - previousRatio;
                    trend = trendChange > 0 ? 'up' : trendChange < 0 ? 'down' : 'flat';
                }
                
                const trendClass = 'trend-' + trend;
                const trendIcon = trend === 'up' ? '<i class="fa fa-caret-up mr-1"></i>' : 
                                 trend === 'down' ? '<i class="fa fa-caret-down mr-1"></i>' : 
                                 '<i class="fa fa-minus mr-1"></i>';
                
                const html = `
                    <div class="highlight-box">
                        <h4>板块配置概览</h4>
                        <div class="info-item">
                            <span class="info-label">板块代码：</span>
                            <span class="info-value">${blockCode}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">最新配置比例：</span>
                            <span class="info-value">${(latestData.blockRatio || 0).toFixed(2)}%</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">环比变化：</span>
                            <span class="info-value">
                                <span class="trend-indicator ${trendClass}">
                                    ${trendIcon}${trendChange > 0 ? '+' : ''}${trendChange.toFixed(2)}%
                                </span>
                            </span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">平均配置比例：</span>
                            <span class="info-value">${avgRatio.toFixed(2)}%</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">最高配置比例：</span>
                            <span class="info-value">${maxRatio.toFixed(2)}%</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">最低配置比例：</span>
                            <span class="info-value">${minRatio.toFixed(2)}%</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">数据记录数：</span>
                            <span class="info-value">${totalRecords} 条</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">数据时间范围：</span>
                            <span class="info-value">${formatDate(data[data.length - 1].reportDate)} 至 ${formatDate(latestData.reportDate)}</span>
                        </div>
                    </div>
                `;
                
                $('#basicInfo').html(html);
            }
            
            // 更新趋势图
            function updateTrendChart(data) {
                if (!data || data.length === 0) {
                    trendChart.setOption({series: [{data: []}]});
                    return;
                }
                
                // 按日期排序
                data.sort((a, b) => new Date(a.reportDate) - new Date(b.reportDate));
                
                // 准备图表数据
                const dates = data.map(item => formatDate(item.reportDate));
                const ratios = data.map(item => item.blockRatio || 0);
                
                // 更新图表
                trendChart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            const data = params[0];
                            return data.name + '<br/>配置比例: ' + data.value + '%';
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: dates,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '配置比例(%)'
                    },
                    series: [{
                        name: '配置比例',
                        type: 'line',
                        smooth: true,
                        data: ratios,
                        itemStyle: {
                            color: '#409eff'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: 'rgba(64, 158, 255, 0.5)'
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(64, 158, 255, 0.1)'
                                }
                            ])
                        }
                    }]
                });
            }
            
            // 更新对比图
            function updateCompareChart(data) {
                if (!data || data.length < 2) {
                    compareChart.setOption({series: [{data: []}]});
                    return;
                }
                
                // 按日期排序，取最近的几个数据点
                data.sort((a, b) => new Date(b.reportDate) - new Date(a.reportDate));
                const recentData = data.slice(0, 6).reverse(); // 取最近6个数据点
                
                // 准备环比数据
                const compareData = [];
                for (let i = 1; i < recentData.length; i++) {
                    const currentRatio = recentData[i].blockRatio || 0;
                    const previousRatio = recentData[i - 1].blockRatio || 0;
                    const change = currentRatio - previousRatio;
                    
                    compareData.push({
                        date: formatDate(recentData[i].reportDate),
                        value: change
                    });
                }
                
                // 更新图表
                compareChart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            const data = params[0];
                            return data.name + '<br/>环比变化: ' + (data.value > 0 ? '+' : '') + data.value + '%';
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: compareData.map(item => item.date)
                    },
                    yAxis: {
                        type: 'value',
                        name: '环比变化(%)'
                    },
                    series: [{
                        name: '环比变化',
                        type: 'bar',
                        data: compareData.map(item => item.value),
                        itemStyle: {
                            color: function(params) {
                                return params.value >= 0 ? '#67c23a' : '#f56c6c';
                            }
                        }
                    }]
                });
            }
            
            // 更新历史数据表
            function updateHistoryTable(data) {
                const tbody = $('#historyTableBody');
                tbody.empty();
                
                if (data && data.length > 0) {
                    // 按日期降序排序
                    data.sort((a, b) => new Date(b.reportDate) - new Date(a.reportDate));
                    
                    data.forEach((item, index) => {
                        // 计算环比变化
                        let change = 0;
                        let trendClass = 'trend-flat';
                        let trendIcon = '<i class="fa fa-minus mr-1"></i>';
                        
                        if (index < data.length - 1) {
                            const nextItem = data[index + 1];
                            change = (item.blockRatio || 0) - (nextItem.blockRatio || 0);
                            
                            if (change > 0) {
                                trendClass = 'trend-up';
                                trendIcon = '<i class="fa fa-caret-up mr-1"></i>';
                            } else if (change < 0) {
                                trendClass = 'trend-down';
                                trendIcon = '<i class="fa fa-caret-down mr-1"></i>';
                            }
                        }
                        
                        const row = $('<tr>');
                        row.append($('<td>').text(formatDate(item.reportDate)));
                        row.append($('<td>').text((item.blockRatio || 0).toFixed(2) + '%'));
                        row.append($('<td>').text((index < data.length - 1) ? 
                            (change > 0 ? '+' : '') + change.toFixed(2) + '%' : '-'));
                        row.append($('<td>').html(index < data.length - 1 ? 
                            '<span class="trend-indicator ' + trendClass + '">' + trendIcon + '</span>' : '-'));
                        row.append($('<td>').text(formatDateTime(item.updateTime)));
                        tbody.append(row);
                    });
                    
                    $('#historyTable').show();
                    $('.loading').hide();
                } else {
                    $('.loading').html('<i class="fa fa-info-circle mr-2"></i><span>暂无数据</span>');
                    $('#historyTable').hide();
                }
            }
            
            // 格式化日期
            function formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.getFullYear() + '-' + 
                       (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                       date.getDate().toString().padStart(2, '0');
            }
            
            // 格式化日期时间
            function formatDateTime(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return formatDate(date) + ' ' + 
                       date.getHours().toString().padStart(2, '0') + ':' + 
                       date.getMinutes().toString().padStart(2, '0') + ':' + 
                       date.getSeconds().toString().padStart(2, '0');
            }
            
            // 响应式处理
            window.addEventListener('resize', function() {
                trendChart.resize();
                compareChart.resize();
            });
        });
    </script>
</body>
</html>